import React, { Component } from "react";
import { Form, Input, Tree } from "antd";
import PropTypes from "prop-types";
import menuList from "../../config/menuConfig";

const Item = Form.Item;
const { TreeNode } = Tree;
export default class AuthForm extends Component {
  static propTypes = {
    role: PropTypes.object,
  };

  constructor(props) {
    super(props);
    //根据角色初始状态生成menus
    const { menus } = this.props.role;
    console.log("wxffffffffffff", typeof menus);
    console.log(
      99999999999,
      menus
        ? menus
            .replaceAll(" ", "")
            .substr(1, menus.replaceAll(" ", "").length - 2)
            ?.split(",") ?? []
        : []
    );
    this.state = {
      checkedKeys: menus
        ? menus
            .replaceAll(" ", "")
            .substr(1, menus.replaceAll(" ", "").length - 2)
            ?.split(",") ?? []
        : [],
    };
  }

  componentWillReceiveProps(next) {
    const menus = next.role.menus;
    console.log(
      "000000000000000000000",
      menus
        ? menus
            .replaceAll(" ", "")
            .substr(1, menus.replaceAll(" ", "").length - 2)
            ?.split(",") ?? []
        : []
    );
    this.setState({
      checkedKeys: menus
        ? menus
            .replaceAll(" ", "")
            .substr(1, menus.replaceAll(" ", "").length - 2)
            ?.split(",") ?? []
        : [],
    });
  }

  // static getDerivedStateFromProps(nextProps, prevState) {
  //   console.log(
  //     "000000000000000000000",
  //     nextProps.role.menus
  //       .substr(1, nextProps.role.menus.length - 2)
  //       ?.split(",") ?? []
  //   );
  //   this.state={
  //     checkedKeys:
  //       prevState.nextProps.role.menus
  //         .substr(1, nextProps.role.menus.length - 2)
  //         ?.split(",") ?? [],
  //   };
  // }
  //父组件获取最新menus
  getMenus = () => this.state.checkedKeys;

  //获得属性数组
  getTreeNodes = (menuList) => {
    return menuList.reduce((pre, item) => {
      //   debugger;
      pre.push(
        <TreeNode title={item.title} key={item.key}>
          {item.children ? this.getTreeNodes(item.children) : null}
        </TreeNode>
      );
      return pre;
    }, []);
  };
  //选中某一个框
  onCheck = (checkedKeys) => {
    this.setState({ checkedKeys });
  };

  componentWillMount() {
    this.treeNode = this.getTreeNodes(menuList);
  }

  render() {
    const { role } = this.props;
    const { checkedKeys } = this.state;
    console.log(1111111111, role);
    return (
      <div>
        <Item label="角色名称" name="name">
          <Input key={role.name} defaultValue={role.name} disabled />
        </Item>
        <Tree
          checkable
          defaultExpandAll={true}
          checkedKeys={checkedKeys} //eval("(" + role.menus + ")")
          onCheck={this.onCheck}
        >
          <TreeNode title="平台权限" key="all">
            {this.treeNode}
          </TreeNode>
        </Tree>
      </div>
    );
  }
}
